<template>
  <el-card style="margin-bottom: 20px">
    <PlusSearch
      v-model="search"
      :columns="pages.search_config.columns"
      :show-number="pages.search_config.showNumber"
      @search="handleSearch"
      @reset="handleReset"
    />
  </el-card>
  <el-card>
    <PlusTable
      :columns="pages.table_config.columns"
      :table-data="tableData"
      :is-selection="true"
      :search="{ labelWidth: '100px', colProps: { span: 8 } }"
      :action-bar="pages.operate_config"
      @clickAction="handleClickButton"
      @selection-change="handleSelectionChange"
    >
      <template #toolbar>
        <el-button
          v-for="item in pages.toolbar_config.columns"
          :key="item.code"
          :type="item.type"
          :size="item.size"
          @click="handleToolbarButton(item)"
          >{{ item.name }}
        </el-button>
      </template>
    </PlusTable>
  </el-card>
  <PlusPagination
    v-model="pagination.pageInfo"
    :total="pagination.total"
    @change="handlePaginationChange"
  />

  <!-- 动态加载并渲染组件 -->
  <component
    :is="dynamicComponent"
    v-if="dynamicComponent"
    :ref="dynamicComp"
    :params="moduleData.params"
    :from_config="moduleData.from_config"
    :businessCode="pages.business_code"
    @search="handleSearch"
  />
</template>

<script lang="ts" setup>
import { usePage } from "./utils/hook";
import { ref, watch } from "vue";
import { findTable } from "@/api/apiJson";
import { SYS_PAGE } from "@/constants/TableNameConstants";
import { PagesProps } from "@/components/Crud/utils/types";

defineOptions({
  name: "Crud"
});
const props = defineProps({
  path: {
    type: String,
    required: true
  },
  search_data: {
    type: Object,
    required: false,
    default: () => {
      return {};
    }
  }
});
const code = ref("");
const searchPropsData = ref({});
watch([code, searchPropsData], async () => {
  const res = await findTable(SYS_PAGE, { code: code.value });
  const pagesProps = res[`${SYS_PAGE}`] as PagesProps;
  await init(pagesProps, searchPropsData.value);
});
code.value = props.path;
searchPropsData.value = props.search_data;
const {
  handleToolbarButton,
  handleSelectionChange,
  moduleData,
  dynamicComp,
  dynamicComponent,
  handleSearch,
  handleReset,
  search,
  pages,
  init,
  tableData,
  pagination,
  handlePaginationChange,
  handleClickButton
} = usePage();
</script>
